﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Common;
using System.IO;

namespace LCRReader
{
    public partial class Display : Form
    {
        DataTable _dt = new DataTable();


        System.Timers.Timer tmr = new System.Timers.Timer(1000);
        I_IO_Card _io = IO_C0640.instance;
        public Display()
        {
            InitializeComponent();
            tmr.Elapsed += tmr_Elapsed;
            tmr.Start();
            _io.TrigEvent += _io_TrigEvent;
        }

        void _io_TrigEvent(ushort obj)
        {
            if ((obj & (1 << 0)) > 0)
            {
                try
                {
                    Invoke(new Action(() =>
            {
                _io.WriteBit(1, true);
                Test();
                _io.WriteBit(1, false);
            }));
                }
                catch (Exception)
                {

                    //   throw;
                }
            }
        }

        void tmr_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            //    throw new NotImplementedException();
            try
            {
                if (InvokeRequired)
                {
                    Invoke(new Action(() =>
                    {

                        this.textBox2.Text = global.Banbie;
                        this.textBox1.Text = global.Line;
                    }));
                }
            }
            catch (Exception ex)
            {
                
               // throw;
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            flowLayoutPanel1.Controls.Add(new usrSpec());
        }

        private void Display_Load(object sender, EventArgs e)
        {
            BindTestConfigs();
            CreateColumns(_dt);
            this.dataGridView1.DataSource = _dt;
        }

        void BindTestConfigs()
        {
            var db = new TestConfigAccess();
            var testConfigs = db.GetAll();
            if (testConfigs != null)
            {
                this.flowLayoutPanel1.Controls.Clear();
                foreach (var a in testConfigs)
                {
                    var spec = new usrSpec() { ID = a.ID, UpperValue = a.Upper, LowerValue = a.Lower, CMD = a.CMD, Enable = a.Enable, Item = a.Name };
                    spec.UpdateUI += BindTestConfigs;
                    this.flowLayoutPanel1.Controls.Add(spec);
                }
            }
        }
        int i = 0;
        public void Test()
        {   
            string ENABLE_COM=GenneralConfigAccess.Inst.GetValue("ENABLE_COMM").ToUpper();
            if (ENABLE_COM != "NA" && ENABLE_COM != "FALSE")
            {
                foreach (var a in this.flowLayoutPanel1.Controls)
                {
                    if (a is usrSpec)
                    {
                        var b = a as usrSpec;
                        if (b.Enable == true)
                        {
                            b.Test();
                        }
                    }
                } 
            }
            IO_C0640.instance.WriteBit(2, true);
            bool Result = global.ResultAll;
            var dr = _dt.NewRow();
            dr.ItemArray = new object[] { ++i, DateTime.Now.ToString("yyyy-MM-dd"), DateTime.Now.ToString("HH:mm:ss"), global.Line, global.Banbie, global.Voltage, global.Current, global.R, Result ? "PASS" : "FAIL" };
             string FileName=Path.Combine(GenneralConfigAccess.Inst.GetValue("SAVE_PATH"),string.Format("Winding {0} {1} {2}.csv",DateTime.Now.ToString("yyyy"),DateTime.Now.ToString("MM"),DateTime.Now.ToString("dd")));

            _dt.Rows.Add(dr);
            _dt.DefaultView.Sort="ID DESC";
            dataGridView1.DataSource = _dt.DefaultView;

            writeCSV(FileName,
        new string[] { 
            DateTime.Now.ToString("yyyy-MM-dd"),
            DateTime.Now.ToString("HH:mm:ss"), 
            global.Line, global.Banbie,
            global.Voltage.ToString(), 
            global.Current.ToString(), 
            global.R.ToString(),
            Result ? "PASS" : "FAIL" });

            var RESULT_ENABLE=GenneralConfigAccess.Inst.GetValue("ENABLE_RESULT").ToUpper();
            if (RESULT_ENABLE == "TRUE")
            {
                IO_C0640.instance.WriteBit(3, Result);
            }
            else
            {
                IO_C0640.instance.WriteBit(3,true);
            }
            IO_C0640.instance.WriteBit(2, false);           
        }

        void CreateColumns(DataTable dataTable)
        {
            if (dataTable.Columns.Count == 0)
            {
                dataTable.Columns.AddRange(new[] { new DataColumn("ID", typeof(int)), new DataColumn("日期"), new DataColumn("时间"), new DataColumn("线别"), new DataColumn("班次") });
                string[] titles = getTitles();
                foreach (var title in titles)
                {
                    dataTable.Columns.Add(new DataColumn(title));
                }
                dataTable.Columns.Add(new DataColumn("判定"));
            }
        }

        string[] getCSVTitiles()
        {
            List<string> list = new List<string>() { "日期", "时间", "线别", "班次" };
            list.AddRange(getTitles());
            list.Add("判定");
            return list.ToArray();
        }

        void writeCSV(string FilePath, string[] infos)
        {
            if (!Directory.Exists(Path.GetDirectoryName(FilePath)))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(FilePath));
            }
            if (!File.Exists(FilePath))
            {
                StreamWriter sw = new StreamWriter(FilePath, true);
                var bstitle = string.Join(",", getCSVTitiles());
                sw.WriteLine(bstitle);
                sw.Close();
            }
            StreamWriter sw1 = new StreamWriter(FilePath, true);
            var bs =string.Join(",", infos);
            sw1.WriteLine(bs);
            sw1.Close();
        }

        string[] getTitles()
        {
            List<string> strs = new List<string>();
            var qs = flowLayoutPanel1.Controls;
            foreach (var q in qs)
            {
                if (q is usrSpec)
                {
                    var c = q as usrSpec;
                    strs.Add(c.Item);
                }
            }
            return strs.ToArray();
        }


        private void button2_Click(object sender, EventArgs e)
        {
            TestConfigAccess db = new TestConfigAccess();
            frmConfig frmConfig = new frmConfig();
            frmConfig.StartPosition = FormStartPosition.CenterScreen;
            frmConfig.Update += BindTestConfigs;
            frmConfig.Show();
            // BindTestConfigs();
        }

        private void 测试_Click(object sender, EventArgs e)
        {
            Test();
        }

    }
}
